<?php
/**
 * 用户频道等级模型类
 */

class UserChannelRankModel extends Model
{
    private $user_channel_rank_id;
    /**
     * 构造函数
     * @author 姜伟
     * @todo 构造函数
     */
    public function __construct($user_channel_rank_id=0)
    {
        parent::__construct();
        $this->user_channel_rank_id = $user_channel_rank_id;
    }


    public function getUserChannelRankInfo($where){
        return $this->where($where)->find();
    }


    //增加用户所在频道的经验值，并判断是否可升级
    public function addExp($user_id, $channel_id, $exp_num){
        $where = 'user_id ='.$user_id. ' and channel_id ='.$channel_id;
        $user_channel_rank = $this->getUserChannelRankInfo($where);
        //获取下一等级
        $next_rank = $this->getUserNextChannelRank($user_id, $channel_id);

        $r = $this->where($where)->setInc('exp', $exp_num);
        if($r && $next_rank){
            
            //用户当前经验是否可升级
            $exp = $user_channel_rank['exp'] + $exp_num;
            if($exp >= $next_rank['need_exp']){
                $this->where($where)->save(array('channel_rank_id'=>$next_rank['channel_rank_id']));
            }
        }
        return $r;
    }



    //获取用户下一等级
    public function getUserNextChannelRank($user_id, $channel_id){
        $where = 'user_id ='.$user_id. ' and channel_id ='.$channel_id;
        $user_rank = $this->getUserChannelRankInfo($where);
        $user_exp = intval($user_rank['exp']);
        $next_rank = M('ChannelRank')->where('need_exp >'.$user_exp)->order('need_exp asc')->find();
        log_file('sql='.M('ChannelRank')->getLastSql(), 'next_rank');
        log_file('next_rank='.json_encode($next_rank), 'next_rank');
        return $next_rank;

    }

    public function addUserChannelRank($arr){
        return $this->add($arr);
    }
}
